package server;
import common.*;
import common.CMessage.DataType;
import common.CMessage.MsgType;

import java.net.*;
import java.io.*;

 
public class CMultiServerThread extends Thread {
    private Socket socket = null;
	private CServer o_server;
	
    public CMultiServerThread(Socket socket, CServer o_server) {
    super("CMultiServerThread");
    this.socket = socket;
	this.o_server = o_server;
    }
 
    public void run() {
 
    try {
        ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
        
        CMessage msg = null;
        msg = (CMessage)in.readObject();

        if(msg.e_type==MsgType.HELLO){
        	synchronized(o_server){
	        	if(msg.e_datatype != DataType.CLIENT_NAME){
	        		System.err.println("Wrong Communication Protocol");
	        	}
	        	int nextid = o_server.GetNextAvailableClientId();
	        	if(nextid==-1){
	        		System.err.println("No more id available.");
	        		CMessage msgsnd = new CMessage(MsgType.SERVERFULL);
	        		out.writeObject(msgsnd);
	        	}
	        	else{
	        		o_server.GetClients()[nextid].Setid(nextid);
	        		o_server.GetClients()[nextid].SetName((String) msg.arr_data[0]);
	        		o_server.GetClients()[nextid].SetIP(socket.getInetAddress().getHostName());
		        	o_server.NewClientConnected(nextid);
		        	CMessage msgsnd = new CMessage(MsgType.WELCOME);
		        	msgsnd.i_clientid = nextid;
		        	System.out.println("Player " + nextid + "Connected.");
		        	out.writeObject(msgsnd);
	        	}
        	}
        }
        if(msg.e_type==MsgType.BYE){
        	System.out.println("Client "+ msg.i_clientid + "said BYE");
        }
        if(msg.e_type==MsgType.GETNEXTMSG){
        	if(!o_server.GetClients()[msg.i_clientid].q_msg_out.isEmpty())
        		out.writeObject(o_server.GetClients()[msg.i_clientid].q_msg_out.poll());
        	else
        		out.writeObject(new CMessage(MsgType.NOMSGAVL));
        }
        if(msg.e_type==MsgType.CLIENTMSG){
        	synchronized(o_server){
	        	o_server.GetClients()[msg.i_clientid].q_msg_in.add(msg);
	        	CMessage msgsnd = new CMessage(MsgType.ACK_RCV);
	        	msgsnd.l_msgid = msg.l_msgid;
	    		out.writeObject(msgsnd);
	    		o_server.notifyAll();
        	}
        }
        out.close();
        in.close();
        socket.close();
 
    } 
    catch (IOException e) {
    	if(!this.isInterrupted())
    		e.printStackTrace();
    } 
    catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
    }
}